// index.js
const app = getApp()
const util = require('../../utils/util')
const _ = wx.cloud.database().command

Page({
  data: {
    //用户信息
    newUser: false,
    hasUserInfo: false,
    building: '',
    floor: '',
    nickName: '',
    avatarUrl: '',
    room: '',
    xid: {},
    xName: {
      'zid': 'water',
      'tid': 'toilet',
      'wid': 'washroom',
      'lid': 'laundry'
    },
    //功能参数
    token: {},
    maxRank: {},
    timeout: {},
    waitingAvailable: {},
    waitingRank: {},
    lastUserNickName: {},
    lastUserTime: {},
    lastUserRoom: {},
    lastUserAvatarUrl: {},
    lastUserTimeout: {},
    //打水额外参数
    temperatureShow: false,
    temperature: '99.0',
    pastTime: null,
    //环境参数
    envInfo: null,
    //页面元素相关
    angle: 0,
    animation: '',
    animationStatus: true,
    notice: '',
    showDebugInfo: false,
    showUpdateInfo: false,
    //刷新控制
    lastRefreshTime: null,
  },

  onLoad: function () {
    app.watch(this.onHasUserInfoChange)
  },

  onReady: function () {
    let that = this;
    that.updateVersion()
    wx.onAccelerometerChange(function (res) {
      var angle = -(res.x * 30).toFixed(1);
      if (angle > 14) {
        angle = 14;
      } else if (angle < -14) {
        angle = -14;
      }
      if (that.data.angle !== angle) {
        that.setData({
          angle: angle
        });
      }
    });
  },

  onShow: function () {
    this.onHasUserInfoChange()
    let query = wx.createSelectorQuery()
    query.select('.container').boundingClientRect((res) => {
      let check_height = parseInt(res.height);
      if (check_height < this.data.autoheight) {
        check_height = this.data.autoheight;
      }
      this.setData({
        autoheight: parseInt(check_height) + "px"
      })
    }).exec()
  },
  onHasUserInfoChange() {
    let that = this
    that.setData({
      building: app.globalData.building,
      floor: app.globalData.floor,
      nickName: app.globalData.nickName,
      avatarUrl: app.globalData.avatarUrl,
      room: app.globalData.room,
      xid: app.globalData.xid,
      hasUserInfo: app.globalData.hasUserInfo,
      newUser: app.globalData.newUser,
      timeout: app.globalData.timeout,
      maxRank: app.globalData.maxRank,
    })
    if (that.data.xid['zid'] != null) {
      that.setData({
        temperatureShow: app.globalData.temperatureZone.includes(that.data.xid['zid'])
      })
    }
    that.onPullDownRefresh(true)
    that.getNotice()
    that.showUpdateInfo()

  },
  // 页面相关事件处理函数--监听用户下拉动作 
  onPullDownRefresh: function (force) {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading()
    let that = this
    if (that.data.temperatureShow) {
      that.getTemperature()
    }
    if (that.data.lastRefreshTime != null && !force) {
      if (new Date().getTime() - that.data.lastRefreshTime.getTime() < 509 * 10) {
        console.log('刷新过于频繁')
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh()
        return 0
      }
    }
    that.setData({
      lastRefreshTime: new Date()
    })
    for (let xid_str in that.data.xName) {
      let mode_str = that.data.xName[xid_str]
      if (that.data.xid[xid_str] != null) {
        that.getToken(mode_str, xid_str).then(function (res) {
          let token = res[1]
          that.setData({
            ['token.' + mode_str]: token
          })
        })
      } else {
        that.setData({
          ['token.' + mode_str]: 1
        })
      }
    }
    setTimeout(function () {
      wx.hideNavigationBarLoading()
    }, 2022)
    wx.stopPullDownRefresh()
  },
  getTemperature() {
    // 获取温度与上次打水结束的时间 
    let that = this
    wx.cloud.database().collection("water")
      .where({
        zid: that.data.xid['zid'],
        token: 2
      })
      .orderBy('time', 'desc').limit(1)
      .get({
        success(result) {
          if (result.data.length > 0) {
            // 计算水温 
            //console.log(result)
            let lastWaterTime = new Date(result.data[0].time).getTime()
            let nowTime = new Date().getTime()
            //console.log(lastWaterTime)
            let pastTime = (nowTime - lastWaterTime) / 1000
            let temperature = that.calculateTemperature(pastTime)
            //console.log("pastTime", pastTime)
            that.setData({
              temperature: temperature,
              pastTime: pastTime.toFixed(0)
            })
          } else {
            that.setData({
              temperature: null,
            })
          }
        }
      })
    return that.data.temperature
  },
  getToken(mode_str, xid_str) {
    // 0 占用中 1 允许使用 2 正在使用 -1 暂时禁用 3 预约中 4 预约已取消
    let that = this
    that.setData({
      ['lastUserTimeout.' + mode_str]: false
    })
    let p1 = new Promise((resolve, reject) => {
      that.checkWaitingQueue(mode_str, xid_str).then(function (waitingAvailable) {
        that.setData({
          ['waitingAvailable.' + mode_str]: waitingAvailable
        })
        resolve(true)
      })
    })
    let p2 = new Promise((resolve, reject) => {
      wx.cloud.database().collection(mode_str)
        .where({
          [xid_str]: that.data.xid[xid_str],
          token: _.in([1, 2])
        })
        .orderBy('time', 'desc')
        .limit(1)
        .get({
          success(result) {
            if (result.data.length > 0) {
              // 由于where的限制 此时的token只可能是 1，2
              let token = result.data[0].token
              if (token == 1) {
                // 允许使用
                resolve(1)
              } else if (token == 2) {
                if (result.data[0].uid == app.globalData.openID) {
                  // 自己正在使用
                  resolve(2)
                } else {
                  let lastTimestamp = result.data[0].time
                  // 此时不是自己在使用
                  that.setData({
                    ['lastUserNickName.' + mode_str]: result.data[0].nickName,
                    ['lastUserTime.' + mode_str]: util.getDateDiff(result.data[0].time),
                    ['lastUserRoom.' + mode_str]: result.data[0].room,
                    ['lastUserAvatarUrl.' + mode_str]: result.data[0].avatarUrl
                  })
                  // 检查排队队列
                  wx.cloud.database().collection(mode_str)
                    .where({
                      [xid_str]: that.data.xid[xid_str],
                      token: 3
                    })
                    .limit(that.data.maxRank[mode_str] || 0)
                    .get({
                      success(result) {
                        if (result.data.length > 0) {
                          let isWaiting = false
                          for (let i = 0; i < result.data.length; i++) {
                            let record = result.data[i]
                            if (record.uid == app.globalData.openID) {
                              isWaiting = true
                              that.setData({
                                ['waitingRank.' + mode_str]: i + 1
                              })
                              if (i == 0) {
                                // 当前为排队第一位 检查正在使用的用户是否超时
                                let nowTime = new Date().getTime()
                                let lastTimeStamp = Date.parse(lastTimestamp)
                                let diffTime = (nowTime - lastTimeStamp) / 1000 // 超时自动释放
                                if (diffTime > that.data.timeout[mode_str]) {
                                  that.setData({
                                    ['lastUserTimeout.' + mode_str]: true
                                  })
                                  resolve(1)
                                }
                              }
                            }
                          }
                          if (isWaiting) {
                            resolve(3)
                          } else {
                            resolve(0)
                          }
                        } else {
                          // 检查正在使用的用户是否超时
                          let nowTime = new Date().getTime()
                          let lastTimeStamp = Date.parse(lastTimestamp)
                          let diffTime = (nowTime - lastTimeStamp) / 1000 // 超时自动释放
                          if (diffTime > that.data.timeout[mode_str]) {
                            that.setData({
                              ['lastUserTimeout.' + mode_str]: true
                            })
                            resolve(1)
                          } else {
                            resolve(0)
                          }
                        }
                      }
                    })
                }
              } else if (token == -1) {
                // 暂时停用
                resolve(-1)
              }
            } else {
              // 数据库中无记录 直接允许使用
              resolve(1)
            }
          }
        })
    })
    return Promise.all([p1, p2])
  },
  onTap(event) {
    let that = this
    let mode_str = event.target.dataset.mode
    let xid_str = event.target.dataset.xid
    if (that.data.xid[xid_str] == null) {
      that.toggle()
      wx.showToast({
        title: '该功能对您不适用',
        icon: 'none',
        duration: 2000
      })
    } else {
      wx.showLoading()
      that.getToken(mode_str, xid_str).then(function (res) {
        let token = res[1]
        if (token == 1) {
          that.setData({
            ['lastUserTimeout.' + mode_str]: false
          })
          // 允许使用盥洗室 添加使用记录
          wx.cloud.database().collection(mode_str)
            .where({
              uid: app.globalData.openID,
              token: 3
            })
            .update({
              data: {
                token: 5,
                time: wx.cloud.database().serverDate()
              },
              success(res) {
              }
            })
          wx.cloud.database().collection(mode_str).add({
            data: {
              uid: app.globalData.openID,
              nickName: that.data.nickName,
              avatarUrl: that.data.avatarUrl,
              room: that.data.room,
              [xid_str]: that.data.xid[xid_str],
              time: wx.cloud.database().serverDate(),
              token: 2
            },
            success(res) {
              that.setData({
                ['token.' + mode_str]: 2
              })
              wx.hideLoading()
            },
          })
        } else if (token == 2) {
          // 使用结束
          wx.cloud.database().collection(mode_str)
            .where({
              token: 3,
              [xid_str]: that.data.xid[xid_str],
            })
            .limit(1)
            .get({
              success(result) {
                // 若队列里有下一位 修改其token 并通知他
                if (result.data.length > 0) {
                  wx.cloud.database().collection(mode_str)
                    .where({
                      uid: result.data[0].uid,
                      token: 3
                    })
                    .update({
                      data: {
                        token: 2,
                        time: wx.cloud.database().serverDate()
                      },
                      success(res) {
                        that.onPullDownRefresh()
                        that.sendMessage(result.data[0].uid, mode_str)
                      }
                    })
                } else {
                  // 添加结束记录
                  wx.cloud.database().collection(mode_str).add({
                    data: {
                      uid: app.globalData.openID,
                      nickName: that.data.nickName,
                      avatarUrl: that.data.avatarUrl,
                      room: that.data.room,
                      [xid_str]: that.data.xid[xid_str],
                      time: wx.cloud.database().serverDate(),
                      token: 1
                    },
                    success(res) {
                      that.setData({
                        ['token.' + mode_str]: 1
                      })
                      wx.hideLoading()
                    }
                  })
                }
              }
            })
          wx.hideLoading()
        }
        else {
          wx.showToast({
            title: '请下拉刷新重试',
            icon: 'none'
          })
        }
      })
    }
  },
  checkWaitingQueue(mode_str, xid_str) {
    let that = this
    // 返回是否可以排队
    if (that.data.maxRank[mode_str] < 0.5) {
      new Promise((resolve, reject) => {
        resolve(false)
      })
    }
    return new Promise((resolve, reject) => {
      wx.cloud.database().collection(mode_str)
        .where({
          [xid_str]: that.data.xid[xid_str],
          token: 3
        })
        .count()
        .then(res => {
          if (res.total >= that.data.maxRank[mode_str]) {
            resolve(false)
          } else {
            that.setData({
              ['waitingRank.' + mode_str]: res.total + 1
            })
            resolve(true)
          }
        })
    })
  },
  addWaitingQueue(event) {
    let that = this
    let mode_str = event.target.dataset.mode
    let xid_str = event.target.dataset.xid
    wx.requestSubscribeMessage({
      tmplIds: ['JsMqLtQBsOFi6t0eKKwBqfSuUe9xSs9Yi__fYqSFRHE'],
      success(res) { console.log(res) },
      fail(err) { console.log(err) }
    })
    wx.showLoading()
    that.getToken(mode_str, xid_str).then(function (res) {
      let token = res[1]
      that.setData({
        ['token.' + mode_str]: token
      })
      that.checkWaitingQueue(mode_str, xid_str).then(function (res) {
        if (token == 0 && that.data.waitingAvailable[mode_str]) {
          // 可以预约
          wx.cloud.database().collection(mode_str).add({
            data: {
              uid: app.globalData.openID,
              nickName: that.data.nickName,
              avatarUrl: that.data.avatarUrl,
              room: that.data.room,
              [xid_str]: that.data.xid[xid_str],
              time: wx.cloud.database().serverDate(),
              token: 3
            },
            success(res) {
              that.setData({
                ['token.' + mode_str]: 3
              })
              wx.hideLoading()
            }
          })
        } else {
          // 不可以预约
          wx.showToast({
            title: '请下拉刷新重试',
            icon: 'none'
          })
        }
      })
    })

  },
  cancelWaiting(event) {
    let that = this
    let mode_str = event.target.dataset.mode
    let xid_str = event.target.dataset.xid
    wx.showLoading()
    wx.cloud.database().collection(mode_str)
      .where({
        uid: app.globalData.openID,
        token: 3
      })
      .update({
        data: {
          token: 4,
          time: wx.cloud.database().serverDate()
        },
        success(res) {
          that.getToken(mode_str, xid_str).then(function (res) {
            let token = res[1]
            that.setData({
              ['token.' + mode_str]: token
            })
          })
          wx.hideLoading()
        }
      })
  },
  sendMessage(target_user, mode_str) {
    let mode_name;
    if (mode_str == 'washroom') {
      mode_name = '盥洗室'
    }
    if (mode_str == 'toilet') {
      mode_name = '卫生间'
    }
    if (mode_str == 'water') {
      mode_name = '打水'
    }
    if (mode_str == 'laundry') {
      mode_name = '洗衣房'
    }
    wx.cloud.callFunction({
      name: 'sendMessage',
      data: {
        phrase7: { value: '已到号' },
        thing12: { value: mode_name },
        touser: target_user
      },
    }).then(res => {
      console.log('发送成功:', res);
    }).catch(err => {
      console.log('发送失败:', err)

    })
  },
  getNotice() {
    let that = this
    wx.cloud.database().collection('notice')
      .where({
        'zid': that.data.zid
      })
      .orderBy('time', 'desc')
      .limit(1)
      .get({
        success(result) {
          // console.log(result)
          if (result.data.length > 0 && result.data[0].valid == true) {
            that.setData({
              notice: result.data[0].text
            })
          }
        }
      })
  },
  onRegister() {
    wx.navigateTo({
      url: '../login/login',
    })
  },
  toggle() {
    var that = this;
    wx.vibrateLong();
    that.setData({
      animation: 'shake'
    })
    setTimeout(function () {
      that.setData({
        animation: ''
      })
    }, 1000)
  },
  showUpdateInfo(){
    if(app.globalData.version!=app.globalData.latestVersion){
      this.setData({
        showUpdateInfo: true,
      })
      this.hideUpdateInfo()
      wx.redirectTo({
        url: '/pages/index/index'
      })
    }
  },
  hideUpdateInfo(){
    let that=this
    wx.cloud.database().collection('users').where({
      _openid: app.globalData.openID
    }).update({
      data: {
        version: wx.getAccountInfoSync().miniProgram.version
      },
      success(res) {
        that.setData({
          showUpdateInfo: false,
        })
      }
    })
  },
  showDebugInfo() {
    wx.setClipboardData({
      data: app.globalData.openID,
    })
    this.setData({
      showDebugInfo: true,
      envInfo: wx.getAccountInfoSync()
    })
  },
  hideDebugInfo() {
    this.setData({
      showDebugInfo: false,
    })
  },
  removeUserInfo() {
    let that=this
    let diffTime = (new Date().getTime() - Date.parse(app.globalData.registerTime)) / 1000 
    if (diffTime < 60*10) {
      wx.showModal({
        content:'暂时无法注销账号\r\n请10分钟后重试',
        showCancel: false
      })
    }else{
      wx.showModal({
        content:'您即将注销账号',
        cancelText: '取消',
        confirmText: '确认',
        success(response) {
          wx.cloud.database().collection('users').where({
            _openid: app.globalData.openID
          })
          .remove({
            success: function() {
              wx.showToast({
                title: '账号已注销',
              })
              that.hideDebugInfo()
              app.globalData.newUser = true
              that.setData({
                newUser: app.globalData.newUser
              })
            },
            fail: console.error
          })
        }
      })
    }
  },
  updateVersion() {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      updateManager.applyUpdate()
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
  },
  calculateTemperature(time) {
    // 从这里计算结束打水到现在是什么时间，以秒为单位
    // 考虑到同学们打完水回宿舍和点击延迟等设置
    // 可以设置为一定范围内的随机数，然后设置一个反馈机制
    // 对某个随机数来说是否准确，然后进行offset的更新
    let offset = 0
    let a = 99.4640739936753
    let b = -0.41260799107128
    let c = 0.00178284183000456
    let d = -2.77918681384406E-06
    let e = 1.61064991014765E-09
    // 利用多项式拟合的结果来计算当前温度
    let temperature = a + b * time + c * time * time + d * time * time * time + e * time * time * time * time
    if (temperature >= 99) {
      temperature = 99
    } else if (temperature < 50) {
      temperature = 50
    }
    return temperature.toFixed(1)
  },
  // 分享页面
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '科学防疫，共克时艰！'
        })
      }, 2000)
    })
    return {
      title: '科学防疫，共克时艰！',
      path: '/pages/index2/index2',
      imageUrl: 'https://tju-spring-memory-1259235122.cos.ap-shanghai.myqcloud.com/dundundun.jpg',
      promise
    }
  },
  onShareTimeline: function (res) {
    return {
      title: '科学防疫，共克时艰！',
      path: '/pages/index2/index2',
      imageUrl: 'https://tju-spring-memory-1259235122.cos.ap-shanghai.myqcloud.com/dundundun.jpg',
    }
  },
});